﻿use std::time::Duration;

use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;
use sqlx::postgres::{PgConnectOptions, PgSslMode};

use crate::{domain::SubscriberEmail, email_client::EmailClient};

#[derive(Deserialize)]
pub struct Settings {
    pub database: DatabaseSettings,
    pub application: ApplicationSettings,
    pub email_client: EmailClientSettings,
    pub redis_uri: SecretString,
}

#[derive(Deserialize, Clone)]
pub struct DatabaseSettings {
    pub username: String,
    pub password: SecretString,
    pub port: u16,
    pub host: String,
    pub database_name: String,
    // 是否要求加密连接
    pub require_ssl: bool,
}

impl DatabaseSettings {
    pub fn connect_options(&self) -> PgConnectOptions {
        use sqlx::ConnectOptions; // 将 sqlx 的日志级别从 info 降低到 trace
        let ssl_mode = if self.require_ssl {
            PgSslMode::Require
        } else {
            PgSslMode::Prefer // 尝试加密连接，如果失败则退回非加密连接
        };
        PgConnectOptions::new()
            .host(&self.host)
            .port(self.port)
            .username(&self.username)
            .password(self.password.expose_secret())
            .ssl_mode(ssl_mode)
            .database(&self.database_name)
            .log_statements(tracing::log::LevelFilter::Trace)
    }
}

#[derive(Deserialize)]
pub struct ApplicationSettings {
    pub host: String,
    pub port: u16,
    pub base_url: String,
    pub hmac_secret: SecretString,
}

/// 分层配置：一个基础配置 + 一组特定于环境的配置（基础配置上的定制字段） + 一个环境变量（确定运行环境）。
/// 目的：在不同环境用不同的配置启动服务。
pub fn get_configuration() -> Result<Settings, config::ConfigError> {
    let base_path = std::env::current_dir().expect("Failed to determine the current directory");
    let configuration_dir = base_path.join("configuration");
    // 检查运行环境
    // 如果没有指定，则默认是 local
    let environment: Environment = std::env::var("APP_ENVIRONMENT")
        .unwrap_or("local".into())
        .try_into()
        .expect("Failed to parse APP_ENVIRONMENT");
    let environment_filename = format!("{}.toml", environment.as_str());

    let setting = config::Config::builder()
        .add_source(config::File::from(configuration_dir.join("base.toml")))
        .add_source(config::File::from(
            configuration_dir.join(environment_filename),
        ))
        // 环境变量中添加设置：前缀 APP，分割符 __
        // 比如：APP_APPLICATION__PORT 可以设置 Settings.application.port
        .add_source(
            config::Environment::with_prefix("APP")
                .prefix_separator("_")
                .separator("__"),
        )
        .build()?;
    setting.try_deserialize::<Settings>()
}

pub enum Environment {
    Local,
    Ssh,
    Production,
}

impl Environment {
    pub fn as_str(&self) -> &'static str {
        match self {
            Environment::Local => "local",
            Environment::Ssh => "ssh",
            Environment::Production => "production",
        }
    }
}
impl TryFrom<String> for Environment {
    type Error = String;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        match value.to_lowercase().as_str() {
            "local" => Ok(Environment::Local),
            "ssh" => Ok(Environment::Ssh),
            "production" => Ok(Environment::Production),
            other => Err(format!(
                "{} is not a supported environment. Use either 'local' or 'production'.",
                other
            )),
        }
    }
}

#[derive(Deserialize)]
pub struct EmailClientSettings {
    pub base_url: String,
    pub path: String,
    pub sender_email: String,
    pub api_user: SecretString,
    pub api_key: SecretString,
    pub timeout_milliseconds: u64,
}

impl EmailClientSettings {
    pub fn client(&self) -> EmailClient {
        let sender_email = self.sender().expect("Invalid sender email address.");
        EmailClient::new(
            sender_email,
            &self.base_url,
            &self.path,
            self.api_user.clone(),
            self.api_key.clone(),
            self.timeout(),
        )
    }
    pub fn sender(&self) -> Result<SubscriberEmail, String> {
        SubscriberEmail::parse(self.sender_email.clone())
    }
    pub fn timeout(&self) -> Duration {
        Duration::from_millis(self.timeout_milliseconds)
    }
}
